package com.xiaochun.hxhj;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.adapter.MyVourseRecyclerViewAdapter;
import com.bean.CourseListBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.myview.CustomProgressDialog;
import com.myview.PullLoadMoreRecyclerView;
import com.util.ExitAppUtil;
import com.util.GlideUtils;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
//启动页一张图片3到5秒------视频页面（第一次）---首页---------（修改密码）

public class MyCourseActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.ll_rebacka)
    LinearLayout ll_rebacka;
    @BindView(R.id.course_data)
    PullLoadMoreRecyclerView course_data;
    @BindView(R.id.tv_titleone)
    TextView tv_titleone;
    @BindView(R.id.tv_mounting)
    TextView tv_mounting;
    @BindView(R.id.img_study_date)
    ImageView img_study_date;


    private String id;
    private CustomProgressDialog customProgressDialog;
    private CourseListBean.DataBeanX courseList = null;
    private List<CourseListBean.DataBeanX.AgoBean.DataBean> agolist = new ArrayList<>();
    private List<CourseListBean.DataBeanX.AgoBean.DataBean> tempagolist = new ArrayList<>();
    private LinearLayoutManager layoutManager;
    private View loadMoreShopView;
    private View notMoreShopView;
    private MyVourseRecyclerViewAdapter adapter;
    private View bottomView;
    private View titleview;
    private TextView tv_today_course_title;
    private TextView tv_today_course_name;
    private TextView tv_today_course_num;
    private LinearLayout ll_stars;
    private View lasttitleview;
    private TextView tv_into_course;
    private int page = 1;
    private ImageView img_invate_feride;
    private ImageView img_studylist;
    private int pagecount = 10;
    private LinearLayout loadLlay;
    private String class_image;

   /* @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }*/

    @Override
    protected void initListener() {
        ll_rebacka.setOnClickListener(this);
        img_studylist.setOnClickListener(this);
        tv_into_course.setOnClickListener(this);
        img_invate_feride.setOnClickListener(this);
        img_study_date.setOnClickListener(this);
        course_data.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData();
            }

            @Override
            public void onLoadMore() {
                if (agolist.size() >= pagecount){
                    page++;
                    getData();
                }else{
                    course_data.setPullLoadMoreCompleted();
                }
            }

            @Override
            public void onScrollChanged(int heightTotal) {
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
//                MyLog.e("第一个可见条目",firstVisibleItemPosition+"    条目");
                if (firstVisibleItemPosition > 0) {
                    tv_mounting.setVisibility(View.VISIBLE);
                } else {
                    tv_mounting.setVisibility(View.GONE);
                }
            }

            @Override
            public void onScrollState(int type) {

            }
        });
        adapter.setOnItemClickListener(new MyVourseRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

                Intent intent = new Intent(context, AnswerQueActivity.class);
                int catelog_id = agolist.get(position).getCatelog_id();
                int course_id = agolist.get(position).getCourse_id();
                String namea = agolist.get(position).getName();
                String names = agolist.get(position).getNames();
                String title = agolist.get(position).getTitle();

                intent.putExtra("course_id", course_id + "");
                intent.putExtra("catelog_id", catelog_id + "");
                intent.putExtra("course_title", title + "");
                intent.putExtra("course_content", namea + "");
                startActivity(intent);

            }
        });
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_mycourse;
    }

    @Override
    protected void initView() {

        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();

        changeTitle("首页");
        showRightView(false);
        hideTitleBar();
//        saveUserInfo("bookid","1");
        id = getIntent().getStringExtra("id");
        adapter = new MyVourseRecyclerViewAdapter(agolist, context);
        setHeader(course_data);
        course_data.setAdapter(adapter);
        course_data.setLinearLayout();
        course_data.setRefreshing(true);
        layoutManager = (LinearLayoutManager) course_data.getLayoutManager();
//        GridLayoutManager gridLayoutManager = homedataRecycleView.getGridLayoutManager();
        course_data.cancleAnimal();
        loadMoreShopView = View.inflate(context, R.layout.item_moredata, null);
        notMoreShopView = View.inflate(context, R.layout.item_nodata, null);
        initTopView();


        getData();

    }

    /**
     * 设置头部布局
     *
     * @param view
     */
    private void setHeader(PullLoadMoreRecyclerView view) {
        //顶部内容
//        titleview = View.inflate(context, R.layout.item_course_title, null);
        titleview = LayoutInflater.from(context).inflate(R.layout.item_course_title, view, false);
        adapter.setBannerView(titleview);
        //往期课程
        lasttitleview = LayoutInflater.from(context).inflate(R.layout.item_last_title, view, false);
        adapter.setRecommendView(lasttitleview);

        //底部加载更多
        bottomView = LayoutInflater.from(context).inflate(R.layout.main_bottom, view, false);
        adapter.setBottomView(bottomView);
    }

    /**
     * 初始化头部控件
     */
    private void initTopView() {
        tv_today_course_title = titleview.findViewById(R.id.tv_today_course_title);
        tv_today_course_name = titleview.findViewById(R.id.tv_today_course_name);
        img_studylist = titleview.findViewById(R.id.img_studylist);
        tv_today_course_num = titleview.findViewById(R.id.tv_today_course_num);
        tv_into_course = titleview.findViewById(R.id.tv_into_course);
        ll_stars = titleview.findViewById(R.id.ll_stars);
        img_invate_feride = titleview.findViewById(R.id.img_invate_feride);

        //加载更多
        loadLlay = (LinearLayout) bottomView.findViewById(R.id.llay_load);
    }

    @Override
    protected void initData() {

    }


    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.ll_rebacka:
                finish();
                break;
            case R.id.tv_into_course:
                intent = new Intent(context, AnswerQueActivity.class);
                if (courseList != null) {
                    int catelog_id = courseList.getId();
                    int course_id = courseList.getCourse_id();
                    String namea = courseList.getName();
                    String names = courseList.getNames();
                    String title = courseList.getTitle();
                    intent.putExtra("course_id", course_id + "");
                    intent.putExtra("catelog_id", catelog_id + "");
                    intent.putExtra("course_title", title + "");
                    intent.putExtra("course_content", namea + "");
                    startActivity(intent);
                }
                break;
            case R.id.ll_mine:

                break;
            case R.id.img_invate_feride:
                String token1 = getUserInfo("token");
                intent = new Intent(context, WebviewActivity.class);
                intent.putExtra("url", myapp.getSiteurlweb() + "/#/share?token=" + token1);
                MyLog.e("网页网特", "网页网特1111");
                startActivity(intent);
                break;
            case R.id.img_study_date:
                String token = getUserInfo("token");
                intent = new Intent(context, WebviewActivity.class);
                // http://192.168.0.113:8081/#/kalendar  参数：course_id(课程id),token
                intent.putExtra("url", myapp.getSiteurlweb() + "/#/kalendar?token=" + token + "&course_id=" + id);
                MyLog.e("网页网特", "网页网特1111");
                startActivity(intent);
                break;
            case R.id.img_studylist:
                intent = new Intent(context,StudyListActivity.class);
                intent.putExtra("course_id",id);
                startActivity(intent);
                break;

        }

    }

    private void getData() {
        String token = getUserInfo("token");
        String url = myapp.getWebConfig() + "/api/practice/study";
        HashMap<String, String> paramsMap = new HashMap<>();
//        paramsMap.put("id", id);
        paramsMap.put("course_id", id);
        paramsMap.put("token", token);
        paramsMap.put("limit", pagecount+"");
        paramsMap.put("page", page + "");
        MyLog.e("正在学习", "id=" + id + "   token=" + token + "   limit=" + page);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    } else if (jsonObject.getString("code").equals("201")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 5;
                        handler.sendMessage(msg);
                        return;
                    }

                    JSONObject data = jsonObject.getJSONObject("data");
                    class_image = data.getString("class_image");
                    courseList = new Gson().fromJson(data.toString(), new TypeToken<CourseListBean.DataBeanX>() {
                    }.getType());
                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    public Handler handler = new Handler() {

        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);
                    course_data.setPullLoadMoreCompleted();
                    if (obj.contains("暂未录入")) {
                        finish();
                    }
                    break;
                case 1:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    course_data.setPullLoadMoreCompleted();
                    break;
                case 2:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
//                    courseList
                    GlideUtils.loadRoundCircleImage(context,class_image,img_invate_feride);
                    tv_titleone.setText(courseList.getTitle());
                    tv_today_course_title.setText(courseList.getTitles());
                    tv_today_course_name.setText(courseList.getName());
                    tv_today_course_num.setText("学习了" + courseList.getNum() + "遍");
                    int star = courseList.getStar();
                    ll_stars.removeAllViews();
                    for (int i = 0; i < star; i++) {
                        View view = View.inflate(context, R.layout.item_star, null);
                        ll_stars.addView(view);
                    }
                    course_data.setPullLoadMoreCompleted();
                    tempagolist = courseList.getAgo().getData();
                    if (page == 1) {
                        agolist.clear();
                    }
                    agolist.addAll(tempagolist);
                    adapter.setDatas(agolist);
                    if (tempagolist.size() == 0) {
                        page--;
                    }
                    loadLlay.removeAllViews();
                    if (tempagolist.size() < pagecount){
                        if (page > 1){
                            loadLlay.addView(notMoreShopView);
                        }
                    }else{
                        loadLlay.addView(loadMoreShopView);
                    }
                    break;
                case 3:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }

                    break;
                case 4:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    break;
                case 5:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    String obj1 = (String) msg.obj;
                    ToastUtils.show(obj1);
                    course_data.setPullLoadMoreCompleted();
                    finish();
                    break;
                case 11:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    sharedPreferences.edit().putString("user_id","").commit();
                    sharedPreferences.edit().putString("username","").commit();
                    sharedPreferences.edit().putString("nickname","").commit();
                    sharedPreferences.edit().putString("mobile","").commit();
                    sharedPreferences.edit().putString("avatar","").commit();
                    sharedPreferences.edit().putString("score","").commit();
                    sharedPreferences.edit().putString("student_id","").commit();
                    sharedPreferences.edit().putString("is_bind_wx","").commit();
                    sharedPreferences.edit().putString("token","").commit();
                    sharedPreferences.edit().putString("is_agent","").commit();
                    sharedPreferences.edit().putString("vip_expire","").commit();
                    sharedPreferences.edit().putString("is_vip","").commit();
                    finish();
                    break;
                case 12:
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                    break;
            }
        }
    };
    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        String paymessage = event.getMessage();
        //0失败   1成功

        if ("设备ID已更新退出登录".equals(paymessage)){
            String type = event.getType();
            ExitAppUtil.getInstance().popbyexit(type,context,MyCourseActivity.this,tv_into_course);
//            popbyexit(type);
        }
    }
}
